package com.redwood.report.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.redwood.report.ItemDecoration.SpaceItemDecoration;
import com.redwood.report.R;
import com.redwood.report.adapter.bak.HuiShouXiangAdapter;
import com.redwood.report.common.Constant;
import com.redwood.report.entity.bak.BaoXiuInfo;
import com.redwood.report.entity.ServiceResult;
import com.redwood.report.entity.bak.been.BaoXiuSearchBeen;
import com.redwood.report.event.ShuaXinEvent;
import com.redwood.report.net.Api;
import com.redwood.report.net.NetUtils;
import com.redwood.report.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;

/**
 * 回收箱
 */
public class HuiShouXiangFragment extends BaseLazyFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener, View.OnClickListener {


    @BindView(R.id.count_tv)
    TextView countTv;
    @BindView(R.id.btn_clear)
    Button btnClear;
    @BindView(R.id.btn_huifu)
    Button btnHuifu;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    private int page = 1;
    private int totalpage = Integer.MAX_VALUE;
    private BaseQuickAdapter homeAdapter;


    /**
     * 布局文件ID（重载）
     *
     * @return
     */
    protected int getLayoutId() {
        return R.layout.fragment_huishouxiang;
    }

    /**
     * 初始化组件（重载）
     */
    protected void initViewData(View entryView) {
        initAdapter();

    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        return super.onCreateView(inflater, container, savedInstanceState);
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShuaXinEvent(ShuaXinEvent event) {
        if(event.dqtype.equals(Constant.CHEXIAO)) {
            onRefresh();
        }
    }
    private void initAdapter() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setColorSchemeColors(Color.rgb(47, 223, 189));
        rvList.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvList.addItemDecoration(new SpaceItemDecoration(getActivity()).setSpace(3f).setSpaceColor(getResources().getColor(R.color.item_press2)));
        homeAdapter = new HuiShouXiangAdapter();
        homeAdapter.setOnLoadMoreListener(this, rvList);
        homeAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {

                }
            }
        });
        homeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ((BaoXiuSearchBeen)adapter.getData().get(position)).setSeleted(!((BaoXiuSearchBeen)adapter.getData().get(position)).isSeleted());
                adapter.notifyItemChanged(position);
            }
        });
        homeAdapter.setEmptyView(R.layout.loading_view, (ViewGroup) rvList.getParent());
        rvList.setAdapter(homeAdapter);
        btnClear.setOnClickListener(this);
        btnHuifu.setOnClickListener(this);
    }

    @Override
    public void onRefresh() {
        page = 1;
        totalpage = Integer.MAX_VALUE;
        loadByServer(false);
    }

    private void loadByServer(final boolean isLoadMore) {
//        totalpage = 30/10;
//        List<BaoXiuBeen> baoXiuBeens = new ArrayList<>();
//        for (int i = 0; i < 10; i++) {
//            BaoXiuBeen baoXiuBeen = new BaoXiuBeen();
//            baoXiuBeens.add(baoXiuBeen);
//        }
//        if (page == 1) {
//            homeAdapter.setNewData(baoXiuBeens);
//        } else {
//            homeAdapter.addData(baoXiuBeens);
//        }
//        page++;
//        if (isLoadMore) {
//            refreshLayout.setEnabled(true);
//            homeAdapter.loadMoreComplete();
//        } else {
//            refreshLayout.setRefreshing(false);
//        }
//        countTv.setText("共计"+homeAdapter.getData().size()+"条");

       /* Api.machine(getActivity(), page, Constant.PAGE_SIZE, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                refreshLayout.setRefreshing(false);
                MachineInfo info = (MachineInfo) rspData;
                if (rspData.getRecode() == 1) {
                    if (page == 1) {
                        homeAdapter.setNewData(info.getData());
                    } else {
                        homeAdapter.addData(info.getData());
                    }
                    homeAdapter.setEmptyView(R.layout.loading_view, (ViewGroup) rvList.getParent());
                    totalpage = info.getCount();
                    page++;
                    if (isLoadMore) {
                        refreshLayout.setEnabled(true);
                        homeAdapter.loadMoreComplete();
                    } else {
                        refreshLayout.setRefreshing(false);
                    }
                } else {
                    if (isLoadMore) {
                        refreshLayout.setEnabled(true);
                        homeAdapter.loadMoreFail();
                    } else {
                        refreshLayout.setRefreshing(false);
                    }
                    Toast.makeText(getActivity(), ((MachineInfo) rspData).getMsg(), Toast.LENGTH_SHORT).show();
                }
                homeAdapter.setEmptyView(R.layout.loading_view, (ViewGroup) rvList.getParent());
            }

            @Override
            public void failed(String msg) {
                if (isLoadMore) {
                    refreshLayout.setEnabled(true);
                    homeAdapter.loadMoreFail();
                } else {
                    refreshLayout.setRefreshing(false);
                }
                Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onUsedCache(String msg) {

            }
        }, MachineInfo.class);*/

        Api.getdelDetail(getActivity(), page, Constant.PAGE_SIZE, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                refreshLayout.setRefreshing(false);
                BaoXiuInfo info = (BaoXiuInfo) rspData;
                if (rspData.getRecode() == 1) {
                        if (page == 1) {
                            homeAdapter.setNewData(info.getData());
                        } else {
                            homeAdapter.addData(info.getData());
                        }
                        homeAdapter.setEmptyView(R.layout.loading_view, (ViewGroup) rvList.getParent());
                        totalpage = (info.getCount() + Constant.PAGE_SIZE - 1) / Constant.PAGE_SIZE;
                        page++;
                        if (isLoadMore) {
                            refreshLayout.setEnabled(true);
                            homeAdapter.loadMoreComplete();
                        } else {
                            refreshLayout.setRefreshing(false);
                        }
                        countTv.setText("共" + info.getCount() + "条");
                }else{
                    ToastUtils.show(rspData.getMsg());
                }
            }

            @Override
            public void failed(String msg) {
                if (isLoadMore) {
                    refreshLayout.setEnabled(true);
                    homeAdapter.loadMoreFail();
                } else {
                    refreshLayout.setRefreshing(false);
                }
                ToastUtils.show(msg);
            }

            @Override
            public void onUsedCache(String msg) {

            }
        }, BaoXiuInfo.class);
    }

    //加载更多
    @Override
    public void onLoadMoreRequested() {
        refreshLayout.setEnabled(false);
        if (page > totalpage) {
            refreshLayout.setEnabled(true);
            homeAdapter.loadMoreEnd(false);
            return;
        } else {
            if (homeAdapter.getData().size() < Constant.PAGE_SIZE) {
                homeAdapter.loadMoreEnd(true);
            } else {
                loadByServer(true);


            }
        }
    }

    @Override
    protected void managerArguments() {

    }

    /**
     * 初始化数据,必须重载（重载）
     */
    protected void initData() {
        loaded();
    }

    /**
     * 第一次页面呈现的时候调用（重载）
     */
    protected void onFirstUserVisible() {
        //初始化数据
        loadByServer(false);
    }

    /**
     * 非第一次页面呈现的时候调用（重载）
     */
    protected void onUserVisible() {

    }

    /**
     * 第一次页面消失的时候调用（重载）
     */
    protected void onFirstUserInvisible() {
    }

    /**
     * 非第一次页面消失的时候调用（重载）
     */
    protected void onUserInvisible() {

    }
//    public void doShouLi(String status){
//        Api.updateStatus(getActivity(), wxid, status,new NetUtils.NetCallBack<ServiceResult>() {
//            @Override
//            public void success(ServiceResult rspData) {
//                if(rspData.getRecode()==1){
//                    //受理
//                    finish();
//                }else{
//                    ToastUtils.show(rspData.getMsg());
//                }
//            }
//
//            @Override
//            public void failed(String msg) {
//                ToastUtils.show(msg);
//            }
//
//            @Override
//            public void onUsedCache(String msg) {
//
//            }
//        }, ServiceResult.class);
//    }
    public void doShouLi(String wxid,String status){
    Api.updateStatus(getActivity(), wxid, status,"",new NetUtils.NetCallBack<ServiceResult>() {
        @Override
        public void success(ServiceResult rspData) {
            if(rspData.getRecode()==1){
                onRefresh();
                EventBus.getDefault().post(new ShuaXinEvent(Constant.WEICHULI));
                EventBus.getDefault().post(new ShuaXinEvent(Constant.ChuLIZHONG));
                EventBus.getDefault().post(new ShuaXinEvent(Constant.YICHULI));
                ToastUtils.show(rspData.getMsg());
            }else{
                ToastUtils.show(rspData.getMsg());
            }
        }

        @Override
        public void failed(String msg) {
            ToastUtils.show(msg);
        }

        @Override
        public void onUsedCache(String msg) {

        }
    }, ServiceResult.class);
}
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_clear:
                ToastUtils.show("服务端不支持此功能");
                break;
            case R.id.btn_huifu:
                List<BaoXiuSearchBeen> baoXiuSearchBeens=homeAdapter.getData();
                for(BaoXiuSearchBeen baoXiuSearchBeen:baoXiuSearchBeens) {
                    if(baoXiuSearchBeen.isSeleted()) {
                        doShouLi(baoXiuSearchBeen.getWxid(),"hf");
                    }
                }
                break;
        }
    }
}
